//
//  CustomProgressBarView.m
//  CoolTennisBall
//
//  Created by Coollang on 16/8/3.
//  Copyright © 2016年 CoolLang. All rights reserved.
//

#import "CustomProgressBarView.h"

@interface CustomProgressBarView ()
/** 渐变色块 */
@property (nonatomic, strong) CAGradientLayer *minTrackLayer;
@property (nonatomic, assign)CGFloat value;
@end

@implementation CustomProgressBarView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.value = 0.0f;
    }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder]) {
         self.value = 0.0f;
    }
    
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    [self setUpUI];
    
}

- (void)updateProgroess:(CGFloat)value {

    if (value < 0) {
        value = 0;
    }else if(value > 1){
        value = 1;
    }
    _value = value;
    CGFloat postionX = value * CGRectGetWidth(self.frame);
    
//    self.minTrackLayer.endPoint = CGPointMake(value, 0.5);
     self.minTrackLayer.startPoint = CGPointMake(1-value, 0.5);
    if (postionX >= 0 && postionX <= self.bounds.size.width) {
        self.minTrackLayer.frame = CGRectMake(0, 0, postionX, self.frame.size.height);
    }
    
}


// 初始化
- (void)setUpUI {
    
    CGFloat postionX = CGRectGetWidth(self.frame) * self.value;
    
    if (postionX >= 0 && postionX <= self.bounds.size.width) {
        [self updateProgroess:self.value];
    }
}

- (void)setColors:(NSArray<UIColor *> *)colors {
    _colors = colors;
    
    if (self.colors.count == 2) {
        self.minTrackLayer.colors = @[(__bridge id)self.colors[0].CGColor,(__bridge id)self.colors[1].CGColor];
    }else if (self.colors.count == 1){
        self.minTrackLayer.colors = @[(__bridge id)self.colors[0].CGColor];
    }
    
}


- (CAGradientLayer *)minTrackLayer {
    if (_minTrackLayer ==nil) {
        CAGradientLayer *minTrackLayer = [[CAGradientLayer alloc] init];
        _minTrackLayer = minTrackLayer;
//        minTrackLayer.startPoint = CGPointMake(0, 0.5);
        minTrackLayer.startPoint = CGPointMake(1, 0.5);
        
        minTrackLayer.endPoint = CGPointMake(1, 0.5);
        
        minTrackLayer.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame));
        
        
        [self.layer addSublayer:_minTrackLayer];
    }
    return _minTrackLayer;
}





@end
